package com.xhh.nphm.api.controller;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xhh.nphm.api.util.ListPageDsCntnr;
import com.xhh.nphm.common.core.controller.BaseController;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class PsMailController extends BaseController
{

  @Resource
  private ForListPage forListPage;

  protected void ajaxResponse(HttpServletResponse response, Object result)
    throws IOException
  {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    Writer out = response.getWriter();

    JSONObject jsObject = JSONObject.fromObject(result);

    out.write(jsObject.toString());
  }

  @RequestMapping("/mail/nopsListJson.ajx")
  public void nopsListJson(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    String pageNo = request.getParameter("pageNum");
    String number = request.getParameter("number");
    String source = request.getParameter("source");
    String status = request.getParameter("status");
    String deptNo = request.getParameter("deptNo");
    if (pageNo == null) {
      pageNo = "1";
    }
    String pageSize = request.getParameter("pageSize");
    if (pageSize == null) {
      pageSize = "10";
    }

    String fieldNames = "t1.id, case when len(cast(t1.body as varchar(8000)))>40 then left(cast(t1.body as varchar(8000)),40)+'...' else t1.body end as summary, t1.author_name as authorName, t1.address, t1.sent_at as sentAt, t2.created_at as instructAt, t3.realname as instructor, t5.realname as source, t1.swift_number as swiftNumber";
    String tabName = "t_ticket t1 left join t_handle_note t2 on t2.ticket_id = t1.id and t2.type = 1  and (t2.del_flag = 0 or t2.del_flag is null) left join t_user t3 on t3.id = t2.user_id LEFT join t_user t5 on t1.owner = t5.mail_box_id INNER join t_mail_box t6 on t6.id = t1.owner INNER join t_organ_structure t7 on t7.id = t6.organ_id ";
    if (StringUtils.isNotBlank(deptNo)) {
      tabName = tabName + "and t7.deptNo = '" + deptNo + "'";
    }
    else {
      tabName = tabName + "and t7.deptNo = ''";
    }

    String pkName = "t1.id";
    String strWhere = "1=1";
    if (StringUtils.isNotBlank(number)) {
      strWhere = strWhere + " and t1.swift_number = '" + number.trim() + "'";
    }
    if (StringUtils.isNotBlank(source)) {
      strWhere = strWhere + " and t5.realname like '%" + source.trim() + "%'";
    }
    if (StringUtils.isNotEmpty(status)) {
      strWhere = strWhere + " and t1.status = " + status;
    }
    String strOrd = "order by t2.created_at desc, t1.import_at desc, t1.id desc";
    ListPageDsCntnr pageListDS = this.forListPage.procedureQuery(pageNo,
      pageSize, fieldNames, tabName, pkName, strWhere, strOrd);
    Map result = new HashMap();
    if ((pageListDS != null) && (pageListDS.getListForPager() != null)) {
      result.put("total", Integer.valueOf(pageListDS.getTotalRecords()));
      result.put("rows", pageListDS.getListForPager());
      result.put("code", 0);
    } else {
      result.put("total", Integer.valueOf(0));
      result.put("rows", new ArrayList());
      result.put("code", 0);
    }

    ajaxResponse(response, result);
  }

  @RequestMapping("/mail/detail12345.do")
  public ModelAndView detail12345(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    ModelAndView mv = new ModelAndView();
    String ticketId = request.getParameter("ticketId");
    String sql = "select t1.*, t2.name as areaStr, t3.name as appealCategoryStr, t4.name as contentCategoryStr, t5.name as ownerName, t5.job_title_name as ownerJobTitle from t_ticket t1 left outer join t_area t2 on t1.area = t2.id left outer join t_appeal_category t3 on t1.help_category = t3.id left outer join t_content_category t4 on t1.content_category = t4.id left outer join t_mail_box t5 on t1.owner = t5.id where t1.id=?";

    String sql2 = "select t1.*, CASE WHEN t1.user_name IS NULL THEN t3.realname ELSE t4.name END AS userName, CASE WHEN t5.name IS NULL THEN t9.name ELSE t5.name END AS userOrganName, CASE WHEN t4.job_title_name IS NULL THEN t8.job_title_name+'秘书' ELSE t4.job_title_name END AS jobTitleName from t_handle_note t1 left outer join t_ticket t2 on t1.ticket_id = t2.id left outer join t_user t3 left outer join t_mail_box t4 inner join t_organ_structure t5 on t4.organ_id=t5.id on t3.mail_box_id = t4.id on t3.id = t1.user_id left outer join t_secretary t6 inner join t_user t7 inner join t_mail_box t8 inner join t_organ_structure t9 on t9.id=t8.organ_id on t7.mail_box_id = t8.id on t6.superior= t7.id on t6.user_id= t3.id where  t1.ticket_id=? and (t1.del_flag = 0 or t1.del_flag is null)";

    List ticket = this.forListPage.queryList(sql, new Object[] { ticketId });
    List handleNoteList = this.forListPage.queryList(sql2, new Object[] { ticketId });

    mv.addObject("detail", ticket.get(0));
    mv.addObject("timeline", handleNoteList);
    mv.setViewName("/system/ticket/detail12345");
    Calendar calendar = Calendar.getInstance();
    String sendAt = (String)((Map)ticket.get(0)).get("sent_at");
    Date date = DateUtils.parseDate(sendAt, new String[] { "yyyy-MM-dd hh:mm:ss", "yyyy-MM-dd hh:mm:ss.S", "yyyy-MM-dd hh:mm:ss.SSS" });
    calendar.setTime(date);
    String someAgo = String.format("%s (%s)", new Object[] { sendAt.substring(0, 16), formatSomeAgo(calendar) });
    mv.addObject("beautifulTime", someAgo);
    return mv;
  }

  private String formatSomeAgo(Calendar calendar)
  {
    long INTERVAL_FIFTEEN_MINUTES = 900000L;
    long INTERVAL_HALF_HOUR = 2L * INTERVAL_FIFTEEN_MINUTES;
    long INTERVAL_HOUR = 2L * INTERVAL_HALF_HOUR;
    long INTERVAL_HALF_DAY = 12L * INTERVAL_HOUR;
    long INTERVAL_DAY = 2L * INTERVAL_HALF_DAY;

    Calendar mCurrentDate = Calendar.getInstance();
    long crim = mCurrentDate.getTimeInMillis();
    long trim = calendar.getTimeInMillis();
    long diff = crim - trim;

    int year = mCurrentDate.get(1);
    int month = mCurrentDate.get(2);
    int day = mCurrentDate.get(5);

    if (diff < 60000L) {
      return "刚刚";
    }
    if ((diff >= 60000L) && (diff < INTERVAL_HOUR)) {
      return String.format("%s分钟前", new Object[] { Long.valueOf(diff / 60L / 1000L) });
    }
    mCurrentDate.set(year, month, day, 0, 0, 0);
    if (trim >= mCurrentDate.getTimeInMillis()) {
      return String.format("%s小时前", new Object[] { Long.valueOf(diff / INTERVAL_HOUR) });
    }
    mCurrentDate.set(year, month, day - 1, 0, 0, 0);
    if (trim >= mCurrentDate.getTimeInMillis()) {
      return "昨天";
    }
    mCurrentDate.set(year, month, day - 2, 0, 0, 0);
    if (trim >= mCurrentDate.getTimeInMillis()) {
      return "前天";
    }
    if (diff < INTERVAL_DAY * 30L) {
      return String.format("%s天前", new Object[] { Long.valueOf(diff / INTERVAL_DAY) });
    }
    if (diff < INTERVAL_DAY * 30L * 12L) {
      return String.format("%s月前", new Object[] { Long.valueOf(diff / (INTERVAL_DAY * 30L)) });
    }
    return String.format("%s年前", new Object[] { Integer.valueOf(mCurrentDate.get(1) - calendar.get(1)) });
  }
}